package com.wsm.common.controller;

import com.wsm.common.config.FilePathConfig;
import com.wsm.common.domain.FileDO;
import com.wsm.common.enums.BaseEnum;
import com.wsm.common.service.FileService;
import com.wsm.common.utils.*;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件上传
 * 
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2017-09-19 16:02:20
 */
@Api(tags = "文件")
@Controller
@RequestMapping("/common/sysFile")
public class FileController extends BaseController {

	@Autowired
	private FileService sysFileService;

	@Autowired
	private FilePathConfig filePathConfig;

	@GetMapping()
	@RequiresPermissions("common:sysFile:sysFile")
	String sysFile(Model model) {
		Map<String, Object> params = new HashMap<>(16);
		return "common/file/file";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("common:sysFile:sysFile")
	public Result<PageUtils> list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<FileDO> sysFileList = sysFileService.list(query);
		int total = sysFileService.count(query);
		PageUtils pageUtils = new PageUtils(sysFileList, total);
		return Result.success(pageUtils);
	}

	@GetMapping("/add")
	@RequiresPermissions("common:sysFile:save")
	String add() {
		return "common/sysFile/add";
	}

	@GetMapping("/edit")
	@RequiresPermissions("common:sysFile:update")
	String edit(Long id, Model model) {
		FileDO sysFile = sysFileService.get(id);
		model.addAttribute("sysFile", sysFile);
		return "common/sysFile/edit";
	}

	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("common:sysFile:info")
	public Result info(@PathVariable("id") Long id) {
		FileDO sysFile = sysFileService.get(id);
		return Result.success();
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("common:sysFile:save")
	public Result save(FileDO sysFile) {
		if (sysFileService.save(sysFile)) {
			return Result.success();
		}
		return Result.error();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("common:sysFile:update")
	public Result update(@RequestBody FileDO sysFile) {
		sysFileService.update(sysFile);
		return Result.success();
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	@RequiresPermissions("common:sysFile:remove")
	public Result remove(Long id, HttpServletRequest request) {
		String fileName = filePathConfig.getUploadPath() + sysFileService.get(id).getUrl().replace("/files/", "");
		if (sysFileService.remove(id) > 0) {
			boolean b = FileUtil.deleteFile(fileName);
			if (!b) {
				return Result.denyMsg("数据库记录删除成功，文件删除失败");
			}
			return Result.success();
		} else {
			return Result.error();
		}
	}

	/**
	 * 删除
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	@RequiresPermissions("common:sysFile:remove")
	public Result remove(@RequestParam("ids[]") Long[] ids) {
		sysFileService.batchRemove(ids);
		return Result.success();
	}

	@ResponseBody
	@PostMapping("/upload")
	Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		String fileName = file.getOriginalFilename();
		fileName = FileUtil.exists(filePathConfig.getUploadPath(), fileName);
		//fileName = FileUtil.renameToUUID(fileName);
		FileDO sysFile = new FileDO(SnowFlake.nextId(), FileType.fileType(fileName), "/files/" + fileName, new Date(), BaseEnum.DEL_FLAF.Not_del.getCode());
		try {
			FileUtil.uploadFile(file.getBytes(), filePathConfig.getUploadPath(), fileName);
		} catch (Exception e) {
			return Result.error();
		}
		if (sysFileService.save(sysFile)) {
			return Result.success(sysFile.getUrl());
		}
		return  Result.error();
	}

	/**
	 * 下载文件
	 * @param request
	 * @param id
	 * @param response
	 */
	@RequestMapping("/downLoadFile")
	void downLoadFile(HttpServletRequest request,Long id,HttpServletResponse response) {
       	byte[] byteArray =null;
       	FileMapUtils fileMapUtils=null;
        try{
            fileMapUtils=sysFileService.downLoadFile(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        String name=(String)fileMapUtils.get("name");
        byteArray=(byte[])fileMapUtils.get("bytes");
		//清除response
		response.reset();
		//设置表头 文件名称
		response.setHeader("Content-Disposition", "attachment; filename="+name);
		//设置编码格式
		response.setContentType("application/octet-stream; charset=UTF-8");
		try {
			//输出流
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			toClient.write(byteArray);
			toClient.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}

}
